<script setup>
import { ref, onMounted, computed } from 'vue';
import * as echarts from 'echarts';

const measureType = ref('fasting');
const chartRef = ref(null);
const avgSugar = ref(5.8);
const maxSugar = ref(7.2);
const minSugar = ref(4.9);

const fluctuation = computed(() => (maxSugar.value - minSugar.value).toFixed(1));

const initChart = () => {
  const chart = echarts.init(chartRef.value);

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '日期: {b0}<br/>血糖: {c0} mmol/L'
    },
    xAxis: {
      type: 'category',
      data: ['6/1', '6/8', '6/15', '6/22', '6/29', '7/6', '7/13']
    },
    yAxis: {
      type: 'value',
      name: '血糖(mol/L)',
      min: 3,
      max: 10,
      axisLine: {
        lineStyle: {
          color: '#67C23A'
        }
      },
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      data: [5.2, 5.8, 6.1, 5.9, 5.7, 6.3, 5.6],
      type: 'line',
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: {
        width: 3,
        color: '#67C23A'
      },
      markLine: {
        silent: true,
        data: [
          { yAxis: 3.9, name: '低血糖' },
          { yAxis: 6.1, name: '正常上限' }
        ],
        label: {
          position: 'end'
        },
        lineStyle: {
          type: 'dashed'
        }
      }
    }]
  };

  chart.setOption(option);
  window.addEventListener('resize', chart.resize);
};

const fetchData = () => {
  console.log('获取血糖数据，测量类型:', measureType.value);
};

onMounted(() => {
  initChart();
  fetchData();
});
</script>

<template>
  <div class="blood-sugar-container">
    <div class="header">
      <h3>血糖监测</h3>
      <el-select v-model="measureType" size="small" @change="fetchData">
        <el-option label="空腹血糖" value="fasting" />
        <el-option label="餐后血糖" value="postprandial" />
        <el-option label="随机血糖" value="random" />
      </el-select>
    </div>

    <div ref="chartRef" class="chart" />

    <div class="stats">
      <el-statistic title="平均血糖" :value="avgSugar" suffix="mmol/L" />
      <el-statistic title="最高血糖" :value="maxSugar" suffix="mmol/L" />
      <el-statistic title="波动范围" :value="fluctuation" suffix="mmol/L" />
    </div>
  </div>
</template>

<style scoped>
.blood-sugar-container {
  padding: 15px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart {
  width: 100%;
  height: 350px;
}

.stats {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
}
</style>